import Redis from 'ioredis';

const redis = new Redis();

const initialData = {
  "1702459181837": '{"title":"sunt aut","content":"quia et suscipit suscipit recusandae","updateTime":"2023-12-13T09:19:48.837Z"}',
  "1702459182837": '{"title":"qui est","content":"est rerum tempore vitae sequi sint","updateTime":"2023-12-13T09:19:48.837Z"}',
  "1702459188837": '{"title":"ea molestias","content":"et iusto sed quo iure","updateTime":"2023-12-13T09:19:48.837Z"}'
}

// 获取所有笔记
export async function getAllNotes() {
  const data = await redis.hgetall('notes');
  if (Object.keys(data).length === 0) {  // notes 哈希表为空
    await redis.hset('notes', initialData);
  }

  return await redis.hgetall('notes');
}

// 添加笔记
export async function addNote(data) {
  const uuid = Date.now().toString();
  await redis.hset('notes', [uuid], data);  // 往 redis 中添加一条 key 为 uuid 值为 data 的数据
  return uuid;
}

// 更新笔记
export async function updateNote(uuid, data) {
  await redis.hset('notes', [uuid], data);
}

// 获取某一篇笔记
export async function getNote(uuid) {
  const data = await redis.hget('notes', uuid);
  return JSON.parse(data);
}

// 删除某一篇笔记
export async function delNote(uuid) {
  const data = await redis.hdel('notes', uuid);
  return data;
}

export default redis;